package com.woniu.car.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.car.annotation.ElasticSearchShopAdd;
import com.woniu.car.common.BeanCopyUtils;
import com.woniu.car.common.OssUtil;
import com.woniu.car.common.ResponseEntity;
import com.woniu.car.config.MyRedisTemplate;
import com.woniu.car.domain.TExamine;
import com.woniu.car.domain.TShops;
import com.woniu.car.dto.*;
import com.woniu.car.exception.AccountException;
import com.woniu.car.exception.ParamException;
import com.woniu.car.exception.StatisticsException;
import com.woniu.car.feignclient.AccountClient;
import com.woniu.car.feignclient.ElasticClient;
import com.woniu.car.mapper.TShopMapper;
import com.woniu.car.param.*;
import com.woniu.car.parameter.ElasticShopUpdateParameter;
import com.woniu.car.service.TExamineService;
import com.woniu.car.service.TShopService;
import com.woniu.car.util.AccountStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WWX
 * @since 2021-06-19
 */
@RestController
@Slf4j
public class TShopServiceImpl extends ServiceImpl<TShopMapper, TShops> implements TShopService {
    @Resource
    private AccountClient accountClient;
    @Resource
    private MyRedisTemplate myRedisTemplate;
    @Resource
    private TExamineService tExamineService;
    @Resource
    private TShopMapper tShopMapper;
    @Resource
    private ElasticClient elasticClient;


    /**
     *@Author 王维鑫
     *@Description 新增商铺信息
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public TShops insertShop(TShops tShops) throws Exception {
        boolean save = this.save(tShops);
        if(save==false){
            throw new Exception("新增商铺信息失败");
        }
        return tShops;
    }
    /**
     *@Author 王维鑫
     *@Description 修改商铺信息
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public TShops updateShop(TShops tShops) {
//        QueryWrapper<TShops> wrapper = new QueryWrapper<>();
//        if(null!=tShops.getShopTel()){
//            wrapper.eq("shop_tel",tShops.getShopTel());
//        }
//        if(null!=tShops.getShopName()){
//            wrapper.eq("shop_name",tShops.getShopName());
//        }
//        if(null!=tShops.getShopStatus()){
//            wrapper.eq("shop_status",tShops.getShopStatus());
//        }
//        if(null!=tShops.getBankCard()&&null!=tShops.getShopBank()){
//            wrapper.eq("bank_card",tShops.getBankCard());
//            wrapper.eq("shop_bank",tShops.getShopBank());
//        }
//        if(null!=tShops.getName()&&null!=tShops.getId()){
//            wrapper.eq("name",tShops.getName());
//            wrapper.eq("id",tShops.getId());
//        }
//        if(null!=tShops.getBusinessTimeClose()){
//            wrapper.eq("business_time_close",tShops.getShopTel());
//        }
//        if(null!=tShops.getShopAddr()){
//            wrapper.eq("shop_addr",tShops.getShopAddr());
//        }
//        if(null!=tShops.getShopDesc()){
//            wrapper.eq("shop_desc",tShops.getShopDesc());
//        }
//        if(0!=tShops.getShopLatitude()&&0!=tShops.getShopLongitude()){
//            wrapper.eq("shop_latitude",tShops.getShopLatitude());
//            wrapper.eq("shop_longitude",tShops.getShopLongitude());
//        }
//        int update = tShopMapper.update(tShops, wrapper);
        boolean b = this.updateById(tShops);
        if(b==false){
            throw new AccountException("修改商铺信息失败");
        }
        System.out.println("商铺信息："+tShops);
        return tShops;
    }




    /**
     *@Author 王维鑫
     *@Description 查询商铺
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public List<TShops> queryShop(TShops tShops) throws ParamException {
        if(tShops==null){
            throw new ParamException("参数不能为空");
        }
        QueryWrapper<TShops> wrapper = new QueryWrapper<>();

        if(null!=tShops.getShopId()){
            wrapper.eq("shop_id", tShops.getShopId());
        }
        if(null!=tShops.getShopName()){
            wrapper.eq("shop_name", tShops.getShopName());
        }
        if(tShops.getShopLatitude()!=0 && tShops.getShopLongitude()!=0){
            wrapper.eq("shop_longitude", tShops.getShopLongitude());
            wrapper.eq("shop_latitude", tShops.getShopLatitude());
        }
        if (null!=tShops.getShopStatus()){
            wrapper.eq("shop_status", tShops.getShopStatus());
        }
        if(null!=tShops.getShopTel()){
            wrapper.eq("shop_tel", tShops.getShopTel());
        }
        List<TShops> list = this.list(wrapper);
        return list;
    }
    /**
     *@Author 王维鑫
     *@Description 基础信息保存
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public ShopBaseInfoDto shopApply(ShopApplyParam param) throws Exception {
        ValueOperations<String, Object> value = myRedisTemplate.opsForValue();
        Object o = value.get("code:" + param.getShopTel());
        String code=o.toString();
        if(code.equals(param.getCode())){
            TShops tShops = new TShops();
            String shopTel = param.getShopTel();
            tShops.setShopTel(shopTel);
            List<TShops> tShops1 = this.queryShop(tShops);
            if(tShops1.size()==0){
                BeanCopyUtils.copyProperties(param,tShops);
                long time = new Date().getTime();
                tShops.setRegistTime(time);
                tShops.setShopStatus(AccountStatus.FORZEN);
                TShops tShops2 = this.insertShop(tShops);
                ShopBaseInfoDto shopBaseInfoDto = new ShopBaseInfoDto();
                BeanCopyUtils.copyProperties(tShops2,shopBaseInfoDto);
                ShopRegistParam shopRegister = new ShopRegistParam();
                BeanCopyUtils.copyProperties(param,shopRegister);
                shopRegister.setShopId(tShops2.getShopId());
                //调用账号服务注册账号
                accountClient.shopRegister(shopRegister);
                return shopBaseInfoDto;
            }else {
                throw new AccountException("该号码已注册，请换其他号码");
            }
        }else {
            throw new AccountException("验证码不对");
        }
    }

    /**
     *@Author 王维鑫
     *@Description 资质文件上传，同步生成待审核信息
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public String qualificationPhotoUpload(MultipartFile multipartFile) throws Exception {
        String upload = OssUtil.upload(multipartFile);
        return upload;
    }


    /**
     *@Author 王维鑫
     *@Description 商铺详细信息上传
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public TShops uploadDetailInfo(ShopDetailedInfoParam param) throws ParamException {
        TShops tShops = new TShops();
        BeanCopyUtils.copyProperties(param,tShops);
        TShops tShops1 = this.updateShop(tShops);
        TShops tShops3 = new TShops();
        tShops3.setShopId(tShops1.getShopId());
        List<TShops> tShops2 = this.queryShop(tShops3);
        return tShops2.get(0);
    }
    /**
     *@Author 王维鑫
     *@Description 查询周边100条商铺数据
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public PageDto queryAroundShop(QueryAroundShopParam param) {
        Page<TShops> tShopsPage = new Page<>();
        QueryWrapper<TShops> tShopsQueryWrapper = new QueryWrapper<>();
        tShopsQueryWrapper.eq("shop_longitude",param.getShopLongitude());
        tShopsQueryWrapper.eq("shop_latitude",param.getShopLatitude());
        Page<TShops> tShopsPage1 = tShopMapper.selectPage(tShopsPage, tShopsQueryWrapper);
        if(null==tShopsPage1){
            throw new AccountException("周边未查到商铺");
        }else {
            PageDto pageDto = new PageDto();
            //当前页
            pageDto.setCurrent(tShopsPage1.getCurrent());
            //每页条数
            pageDto.setSize(tShopsPage1.getSize());
            //总条数
            pageDto.setTotal(tShopsPage1.getTotal());
            pageDto.setList(tShopsPage1.getRecords());
            return pageDto;
        }
    }
    /**
     *@Author 王维鑫
     *@Description 将商铺信息上传到ES
     *@Param
     *@return
     **/
    @ElasticSearchShopAdd
    @Override
    @Transactional
    public void uploadShopInfo(ShopEsParam param) {

    }
    /**
     *@Author 王维鑫
     *@Description 商铺图片上传
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public String  uploadShopImg(MultipartFile multipartFile) throws IOException, ParamException {
        String upload = OssUtil.upload(multipartFile);
         return upload;
    }
    /**
     *@Author 王维鑫
     *@Description 查看营运商铺
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public PageDto queryPassShop() throws ParamException {
        Page<TShops> tShopsPage = new Page<>();
        QueryWrapper<TShops> tShopsQueryWrapper = new QueryWrapper<>();
        tShopsQueryWrapper.eq("shop_status",AccountStatus.NORMAL);
        Page<TShops> tShopsPage1 = tShopMapper.selectPage(tShopsPage, tShopsQueryWrapper);
        if(tShopsPage1.getSize()==0){
            throw new AccountException("未查到营运商铺");
        }else {
            PageDto pageDto = new PageDto();
            //当前页
            pageDto.setCurrent(tShopsPage1.getCurrent());
            //每页条数
            pageDto.setSize(tShopsPage1.getSize());
            //总条数
            pageDto.setTotal(tShopsPage1.getTotal());
            pageDto.setList(tShopsPage1.getRecords());
            return pageDto;
        }
    }
    /**
     *@Author 王维鑫
     *@Description 查看冻结商铺
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public PageDto queryForzenShop() throws ParamException {
        Page<TShops> tShopsPage = new Page<>();
        QueryWrapper<TShops> tShopsQueryWrapper = new QueryWrapper<>();
        tShopsQueryWrapper.eq("shop_status",AccountStatus.FORZEN);
        Page<TShops> tShopsPage1 = tShopMapper.selectPage(tShopsPage, tShopsQueryWrapper);
        if(tShopsPage1.getSize()==0){
            throw new AccountException("未查到营运商铺");
        }else {
            PageDto pageDto = new PageDto();
            //当前页
            pageDto.setCurrent(tShopsPage1.getCurrent());
            //每页条数
            pageDto.setSize(tShopsPage1.getSize());
            //总条数
            pageDto.setTotal(tShopsPage1.getTotal());
            pageDto.setList(tShopsPage1.getRecords());
            return pageDto;
        }
    }
    /**
     *@Author 王维鑫
     *@Description 查看封禁商铺
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public PageDto queryBanShop() throws ParamException {
        Page<TShops> tShopsPage = new Page<>();
        QueryWrapper<TShops> tShopsQueryWrapper = new QueryWrapper<>();
        tShopsQueryWrapper.eq("shop_status",AccountStatus.BAN);
        Page<TShops> tShopsPage1 = tShopMapper.selectPage(tShopsPage, tShopsQueryWrapper);
        if(tShopsPage1.getSize()==0){
            throw new AccountException("未查到营运商铺");
        }else {
            PageDto pageDto = new PageDto();
            //当前页
            pageDto.setCurrent(tShopsPage1.getCurrent());
            //每页条数
            pageDto.setSize(tShopsPage1.getSize());
            //总条数
            pageDto.setTotal(tShopsPage1.getTotal());
            pageDto.setList(tShopsPage1.getRecords());
            return pageDto;
        }
    }
    /**
     *@Author 王维鑫
     *@Description 资质文件地址保存
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public ShopUrlDto saveQualificationUrl(ShopQualificationUrlParam param) throws Exception {
        Photo photo = new Photo();
        photo.setPhotoName(param.getPhotoName());
        photo.setUrl(param.getShopQualificationUrl());
        String s = JSON.toJSONString(photo);
        TShops tShops = new TShops();
        tShops.setShopId(param.getShopId());
        List<TShops> tShops1 = this.queryShop(tShops);
        if(tShops1.size()==0){
            throw new ParamException("未查到商铺信息");
        }else {
            TShops tShops2 = tShops1.get(0);
            tShops2.setShopQualificationsUrl(s);
            this.updateShop(tShops2);
            TShops tShops3 = tShopMapper.selectById(param.getShopId());
            TExamine tExamine = new TExamine();
            System.out.println("审核："+tExamine);
            BeanCopyUtils.copyProperties(tShops3,tExamine);
            tExamineService.insertExamine(tExamine);
            ShopUrlDto shopUrlDto = new ShopUrlDto();
            BeanCopyUtils.copyProperties(tShops2,shopUrlDto);
            return shopUrlDto;
        }
    }
    /**
     *@Author 王维鑫
     *@Description 店铺图片地址保存
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public ShopPhotoUrlDto shopPhotoUrlSave(ShopQualificationUrlParam param) throws ParamException {
        TShops tShops = new TShops();
        tShops.setShopId(param.getShopId());
        List<TShops> tShops1 = this.queryShop(tShops);
        ShopPhotoUrlDto shopPhotoUrlDto = new ShopPhotoUrlDto();
        if(tShops1.size()==0){
            throw new ParamException("未查到商铺信息");
        }else {
            TShops tShops4 = tShops1.get(0);
            String shopPictureUrl1 = tShops4.getShopPictureUrl();
            if(null==shopPictureUrl1){
                ArrayList<Photo> photos = new ArrayList<>();
                Photo photo = new Photo();
                photo.setUrl(param.getShopQualificationUrl());
                photo.setPhotoName(param.getPhotoName());
                photos.add(photo);
                String s = JSON.toJSONString(photos);
                tShops4.setShopPictureUrl(s);
                this.updateShop(tShops4);
                BeanCopyUtils.copyProperties(tShops4,shopPhotoUrlDto);
                return shopPhotoUrlDto;
            }else {
                Photo photo = new Photo();
                photo.setPhotoName(param.getPhotoName());
                photo.setUrl(param.getShopQualificationUrl());
                List<Photo> list = JSONObject.parseArray(shopPictureUrl1, Photo.class);
                list.add(photo);
                String s = JSON.toJSONString(list);
                tShops4.setShopPictureUrl(s);
                BeanCopyUtils.copyProperties(tShops4,shopPhotoUrlDto);
                return shopPhotoUrlDto;
            }
        }
    }
    /**
     *@Author 王维鑫
     *@Description 删除店铺
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public BanShopDto banShop(BanShopParam param) throws StatisticsException {
        //更改店铺状态为封禁
        TShops tShops = new TShops();
        tShops.setShopStatus(AccountStatus.BAN);
        tShops.setShopId(param.getShopId());
        int i = tShopMapper.updateById(tShops);
        TShops tShops1 = tShopMapper.selectById(param.getShopId());
        BanShopDto banShopDto = new BanShopDto();
        BeanCopyUtils.copyProperties(tShops1,banShopDto);
        //ES中删除店铺
        elasticClient.ElasticServerDelete(param.getShopId());
        return banShopDto;
    }
    /**
     *@Author 王维鑫
     *@Description 更新店铺信息
     *@Param
     *@return
     **/
    @Override
    @Transactional
    public ShopInfoDto updateShop(UpdateShopParam param) throws StatisticsException {
        TShops tShops = new TShops();
        BeanCopyUtils.copyProperties(param,tShops);
        TShops tShops1 = this.updateShop(tShops);
        ElasticShopUpdateParameter elasticShopUpdateParameter = new ElasticShopUpdateParameter();
        BeanCopyUtils.copyProperties(param,elasticShopUpdateParameter);
        ResponseEntity responseEntity = elasticClient.ElasticShopUpdate(elasticShopUpdateParameter);
        ShopInfoDto shopInfoDto = new ShopInfoDto();
        BeanCopyUtils.copyProperties(tShops1,shopInfoDto);
        return shopInfoDto;
    }


}
